package com.android.love.ui;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.android.love.R;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.CommonRegex;
import com.android.love.util.LogUtil;
import com.android.love.vo.Address;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewFinder;

public class AddressActivity extends BasePageActivity {
	private ViewFinder addressFinder;
	private EditText et_name;
	private EditText et_address;
	private EditText et_detail_address;
	private EditText et_phone;
	private EditText et_email;
	private EditText et_postcode;
	private long address_id = 0;
	private boolean new_address;
	private Address address;
	private boolean delete_result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View addressView = inflater.inflate(R.layout.activity_address, null);
		addressFinder = new ViewFinder(addressView);
		setContentView(addressView);
		process();
		setListener();
	}

	@Override
	protected Boolean loadBottomTab() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void process() {
		super.process();
		addressFinder.setDrawable(R.id.iv_shuaxin, R.drawable.btn_delete);
		addressFinder.setText(R.id.top_title, "收货地址");
		et_name = addressFinder.find(R.id.et_name);
		et_address = addressFinder.find(R.id.et_address);
		et_detail_address = addressFinder.find(R.id.et_detail_address);
		et_phone = addressFinder.find(R.id.et_phone);
		et_email = addressFinder.find(R.id.et_email);
		et_postcode = addressFinder.find(R.id.et_postcode);
		Intent intent = getCurrentIntent();
		if (intent != null) {
			new_address = intent.getBooleanExtra("new_address", false);
			if (!new_address) {
				address = (Address) intent.getSerializableExtra("address");
				et_name.setText(address.getConsignee());
				et_address.setText(address.getAddress().split(" ")[0]);
				et_detail_address.setText(address.getAddress().split(" ")[1]);
				et_phone.setText(address.getPhone());
				et_email.setText(address.getMail());
				et_postcode.setText(address.getPostal());
			} else {
				hide(addressFinder.find(R.id.iv_shuaxin));
			}

		}
	}

	@Override
	protected void setListener() {
		super.setListener();
		addressFinder.find(R.id.iv_top_meinv).setOnClickListener(this);
		addressFinder.find(R.id.iv_shuaxin).setOnClickListener(this);
		addressFinder.find(R.id.iv_confirm).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_confirm:
			if (TextUtils.isEmpty(et_name.getText().toString().trim())) {
				ActivityUtil.show(AddressActivity.this, "姓名不能为空");
				return;
			}
			if (TextUtils.isEmpty(et_address.getText().toString().trim())) {
				ActivityUtil.show(AddressActivity.this, "地址不能为空");
				return;
			}
			if (TextUtils
					.isEmpty(et_detail_address.getText().toString().trim())) {
				ActivityUtil.show(AddressActivity.this, "详细地址不能为空");
				return;
			}
			if (TextUtils.isEmpty(et_phone.getText().toString().trim())) {
				ActivityUtil.show(AddressActivity.this, "电话不能为空");
				return;
			}
			if (TextUtils.isEmpty(et_postcode.getText().toString().trim())) {
				ActivityUtil.show(AddressActivity.this, "邮编不能为空");
				return;
			}
			if (!CommonRegex.matchPersionName(et_name.getText().toString()
					.trim())) {
				ActivityUtil.show(AddressActivity.this, "姓名无效");
				return;
			}
			if (!CommonRegex.matchCNMobileNumber(et_phone.getText().toString()
					.trim())) {
				ActivityUtil.show(AddressActivity.this, "电话格式错误");
				return;
			}
			if (!TextUtils.isEmpty(et_email.getText().toString().trim())) {
				if (!CommonRegex.matchEmail(et_email.getText().toString()
						.trim())) {
					ActivityUtil.show(AddressActivity.this, "邮箱格式错误");
					return;
				}
			}
			MyRequest req = new MyRequest();
			req.authority = UriHelper.REALM_NAME;
			req.path = UriHelper.URL_ADDRESS_MODIFY;
			req.paramers = generateParams(false);
			getDataFromTask(context, ADDRESS_ADD, req, address_id, true, false);
			break;
		case R.id.iv_top_meinv:
			Intent aintent = new Intent();
			aintent.putExtra("address", address);
			setResult(RESULT_OK, aintent);
			finish(true);
			break;
		case R.id.iv_shuaxin:
			if (new_address)
				return;
			newYesNoDialog(R.string.delete_title, R.string.delete_message,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == DialogInterface.BUTTON_POSITIVE) {
								MyRequest req = new MyRequest();
								req.authority = UriHelper.REALM_NAME;
								req.path = UriHelper.URL_ADDRESS_DELETE;
								req.paramers = generateParams(true);
								getDataFromTask(context, ADDRESS_DELETE, req,
										delete_result, true, false);
							}

						}
					}).show();
			break;

		default:
			break;
		}
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(boolean delete) {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		if (!delete) {
			params.put("address", et_address.getText().toString().trim() + " "
					+ et_detail_address.getText().toString().trim());
			params.put("phone", et_phone.getText().toString().trim());
			// LogUtil.i(TAG, "mail---" + et_email.getText().toString().trim());
			// if ("".equals(et_email.getText().toString().trim()))
			// params.put("mail", " ");
			// else
			params.put("mail", et_email.getText().toString().trim());
			params.put("consignee", et_name.getText().toString().trim());
			params.put("postal", et_postcode.getText().toString().trim());
		}
		params.put("app_key", "android");
		params.put("v", "1.0");
		if (!new_address)
			params.put("address_id", address.getAddress_id() + "");
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		switch (tag) {
		case ADDRESS_ADD:
			if (object != null) {
				address_id = (Long) object;
				Address address = new Address();
				address.setAddress_id(address_id);
				address.setAddress(et_address.getText().toString().trim() + " "
						+ et_detail_address.getText().toString().trim());
				address.setMail(et_email.getText().toString().trim());
				address.setConsignee(et_name.getText().toString().trim());
				address.setPhone(et_phone.getText().toString().trim());
				address.setPostal(et_postcode.getText().toString().trim());
				address.setDefault_address(address.getDefault_address());
				Intent aintent = new Intent();
				aintent.putExtra("address_add", address);
				setResult(RESULT_OK, aintent);
				finish();
			}
			break;
		case ADDRESS_DELETE:
			if (object != null) {
				delete_result = (Boolean) object;
				if (delete_result) {
					// 删除成功
					Intent aintent = new Intent();
					aintent.putExtra("delete", true);
					aintent.putExtra("address", address);
					setResult(RESULT_OK, aintent);
					finish();
				}
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			Intent aintent = new Intent();
			aintent.putExtra("address", address);
			setResult(RESULT_OK, aintent);
			finish(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
